#! /usr/bin/env python
# coding=utf-8

import os
import time
import datetime

import urllib2
import MySQLdb
import MySQLdb.cursors
import ConfigParser
from utils.syslog import Logger
from apscheduler.schedulers.blocking import BlockingScheduler


config = ConfigParser.ConfigParser()
config.read("./conf/config.ini")
logger = Logger(logger="log").getlog()
conn = None
def  getConn():
    conn= MySQLdb.connect(
            host=config.get("mysqldb", "host"),
            port = int(config.get("mysqldb", "port")),
            user=config.get("mysqldb", "user"),
            passwd=config.get("mysqldb", "passwd"),
            db =config.get("mysqldb", "db"),
            cursorclass=MySQLdb.cursors.DictCursor
            )
    return conn

# 获取当前Session
def get_curr_session():
    sql = '''
        select * from nh_grab_session_dict d where now() between begin_time and end_time
    '''
    conn = getConn()
    cr = conn.cursor()
    cr.execute(sql)
    session_obj = cr.fetchone()
    cr.close()
    conn.close()
    return session_obj

# 获取所有session
def get_all_session():
    sql = '''
        select * from nh_grab_session_dict d
    '''
    conn = getConn()
    cr = conn.cursor()
    cr.execute(sql)
    session_list = cr.fetchall()
    cr.close()
    conn.close()
    return session_list

# 写入上一个Session的排行纪录
def write_order_list(pre_session):
    print(pre_session)

    conn = getConn()
    cr = conn.cursor()
    sql = '''
          insert into nh_grab_record_history(openid, level, username, session, score)
            select s.open_id, @rowno:=@rowno + 1 as level, s.list_name, '''
    sql += str(pre_session)
    sql += ''', list_score  from (
          select g.open_id, max(g.record) list_score, p.username list_name, w.headimgurl list_img,
                            date_format(g.ctime, '%Y/%m/%d') list_day,  date_format(g.ctime, '%H:%i') list_time
          from nh_grab_redpackage_record g
            left join wechat_fans w on w.openid = g.open_id
            left join nh_personnel p on g.open_id = p.open_id
          where w.openid is not null and p.oid is not null
          group by g.open_id) s, (select @rowno :=0) t
          order by list_score desc limit 5'''
    cr.execute(sql)
    cr.close()
    conn.commit()
    conn.close()


# 定时发红包，等级红包
def send_red_packet(session):
    url = 'http://localhost/git/php/VcanbioNh/index/grab/grab_wine_red_packet?session=' + str(session);
    opener = urllib2.build_opener()
    request = urllib2.Request(url = url)
    resp = opener.open(request)
    print resp.read()

if __name__ == '__main__':
    scheduler = BlockingScheduler()

    session_list = get_all_session()
    for session_obj in session_list:
        session = session_obj['session']
        end_time = session_obj['end_time']
        export_time = end_time + datetime.timedelta(seconds=1);
        # export_time = datetime.datetime.now() + datetime.timedelta(seconds = 2)
        if session != -1:
            scheduler.add_job(write_order_list, next_run_time=export_time, args=[session])
            send_time = export_time + datetime.timedelta(seconds = 5)
            scheduler.add_job(send_red_packet, next_run_time=send_time, args=[session])

    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        scheduler.shutdown()
